<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>滑动拖拽</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            html,
            body,
            #outer {
                width: 100%;
                height: 100%;
                overflow: hidden;
                position: relative;
            }
            #outer {
                background: #ccc;
            }
            #inner {
                width: 150px;
                height: 200px;
                background: #aef;
                position:absolute;
                left: 0;
                top: 0;
                transition: all 0.3s;
            }
        </style>
    </head>
    <body>
        <div id="outer">
            <div id="inner"></div>
        </div>

        <script>
            let outer = document.querySelector("#outer");
            let inner = document.querySelector('#inner');

            //绑定事件
            inner.addEventListener("touchstart", function(e){
                console.log(e.changedTouches);

                this.one = inner.offsetLeft;
                this.two = e.changedTouches[0].clientX;

                this.yi = inner.offsetTop;
                this.er = e.changedTouches[0].clientY;
            });

            inner.addEventListener("touchmove", function(e){
                //移除过渡
                this.style.transition = 'none';
                let three = e.changedTouches[0].clientX;
                let san = e.changedTouches[0].clientY;
                //计算最终结果
                let newLeft = three - (this.two - this.one);
                let newTop = san - (this.er - this.yi);
                //检测是否越界
                if(newLeft <= 0) newLeft = 0;
                //设置
                inner.style.left = newLeft + 'px';
                inner.style.top = newTop + 'px';
            });

            inner.addEventListener("touchend", function(){
                //增加过渡
                this.style.transition = 'all 0.3s';
                //自动吸附效果
                //中间状态的 left 值
                let middle = (outer.offsetWidth - inner.offsetWidth ) / 2; 
                let newLeft;
                //判断
                if(inner.offsetLeft < middle){
                    //如果偏左, 则left为0
                    newLeft = 0;
                }else{
                    //如果偏右, 则left为
                    newLeft = outer.offsetWidth - inner.offsetWidth;
                }
                //设置
                inner.style.left = newLeft + 'px';
            })

        </script>
        
    </body>
</html>
